<template>
  <div class="parbox">
    <div class="box1">
      <batch-operat-btn
        v-if="editable"
        :isView="false"
        :addData="true"
        addText='选择商品'
        @onAddData="onAddData"
      >
        <template #cusBtn>
          <import-goods-modal @onSubmitData="onImportInfo"></import-goods-modal>
          <export-excel
            ref="export"
            style="marginLeft:20px"
            btnType="link"
            btnText="下载商品数据"
            size="large"
            @getExcelData="onDownloadStore"
          ></export-excel>
        </template>
      </batch-operat-btn>
      <div class="recordBox">
        <a-list-table
          :columns="columns"
          :inputNameObj="inputName"
          :tableData="listdata"
          :isSelecttion="false"
          :loading="loading"
          :scroll="{ y: null }"
          @onAction="onAction"
          @onChangeInput="onChangeInput"
        >
        </a-list-table>
      </div>
    </div>
    <div
      class="box2"
      v-if="0"
    >
      <a-button
        class="btn"
        style="marginRight:20px"
        type="default"
        @click="previous()"
      >
        上一步
      </a-button>
      <a-button
        class="btn"
        type="primary"
        @click="nexts()"
      >
        提交
      </a-button>
    </div>
    <addGoodsModal
      ref="addGoodsModal"
      @onAddInfo="onAddInfo"
    />
  </div>
</template>

<script>
import basicModal from '@/views/app/biz/common/basicModal'
import aListTable from '@/views/app/biz/common/aListTable'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import addGoodsModal from './addGoodsModal'
import importGoodsModal from './importGoodsModal.vue'
import exportExcel from '@/views/app/biz/common/exportExcel/index.vue'
// import { getInfoByPid as getSupplierInfoByPid } from '@/views/app/biz/supplier/supplier'
import { getLicenseByPid, saveOederGoods } from './purchaseOrder'
import { downloadData } from '../purchasedGoods/purchasedgoods'
import moment from 'moment'
import { columnsDetail } from './dataConfig'

export default {
  components: {
    basicModal,
    aListTable,
    batchOperatBtn,
    addGoodsModal,
    importGoodsModal,
    exportExcel
  },
  props: {
    orderData: {
      type: Object,
    },
    supplierOrgPid: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      footer: undefined,
      editable: true,
      loading: false,
      modal: {
        modalVisible: false,
        modalTitle: '添加商品',
        modalWidth: '85vw',
      },
      columns: columnsDetail,
      inputName: [
        { name: 'iunitprice', type: 'text', placeholder: '价格' },
        { name: 'num', type: 'number', placeholder: '数量' },
      ],
      listdata: [],
      listKey: 0,
      changeList: [],
      loadings: false,
    }
  },
  computed: {},
  mounted () { },
  methods: {

    // 关闭模态详细框
    closeModal () {
      this.modal.modalVisible = false
      this.$emit('close')
    },
    //点击选择商品
    onAddData () {
      console.log(this.supplierOrgPid);
      if (this.supplierOrgPid) {
        this.$refs.addGoodsModal.addModal(this.supplierOrgPid)
      } else {
        this.$message.warning({ content: '请先在订单信息中选择供应商' })
      }

    },
    // 子modal提交过来的信息
    onAddInfo (datas) {
      let newArr = []
      outloop:
      for (let item of datas) {
        for (let items of this.listdata) {
          if (items.purProdPid == item.pid) {
            this.$message.warn({ content: item.supplierOrgName + '的商品：' + item.productNameZh + '已添加，请勿重复添加' })
            newArr = []
            break outloop;
          }
        }
        newArr.push({
          key: item.pid,
          action: ['删除'],
          pid: '',
          sysSeq: 0,
          supplierName: item.supplierOrgName,
          purProdPid: item.pid,
          productNameZh: item.productNameZh,
          standardCode: item.standardCode,
          supplierOrgCode: item.supplierOrgCode,
          model: item.model,
          spec: item.spec,
          manufacturerZh: item.manufacturerZh,
          measurement: item.measurement,
          num: item.minPackageNum ? item.minPackageNum : 1,
          iunitprice: item.price,
        })
      }
      console.log(newArr)
      if (newArr.length) {
        this.listdata.push.apply(this.listdata, newArr);
        this.$refs.addGoodsModal.closeModal()
      }

    },
    //下载商品数据到本地
    async onDownloadStore () {
      let pa = { productNameZh: null }
      let res = await downloadData(pa)
      console.log(res)
      if (res) {
        let downFileName = moment(new Date).format("YYYYMMDDhhmmss")
        // let downFileName=record.areaCT+'_'+optTime
        if (typeof window.chrome !== 'undefined') {
          // Chrome version
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          const urls = window.URL.createObjectURL(blob)
          const a = document.createElement('a') // 生成虚拟a标签
          a.href = urls
          a.download = downFileName + '.xlsx'
          a.click()
          // document.body.remove(a) // 下载完成移除元素
          window.URL.revokeObjectURL(urls) // 释放掉blob对象
        } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // IE version
          const blob = new Blob([res], { type: 'application/force-download' })
          window.navigator.msSaveBlob(blob, downFileName)
        } else {
          // Firefox version
          const file = new File([res], downFileName, { type: 'application/force-download' })
          window.open(URL.createObjectURL(file))
        }
      }
    },
    //本地导入商品
    onImportInfo (val) {
      this.listdat = []
      console.log(val);
      let newArr = []
      for (let item of val) {
        newArr.push({
          ...item,
          key: item.key,
          pid: '',
          sysSeq: 0,
          action: ['删除'],
          purProdPid: item.pid,
        })
      }
      console.log(newArr);
      this.listdata = newArr
    },
    previous () {
      this.$emit("onCancel")
    },
    skip () {
      this.$emit("onSkip", 4)
    },
    nexts () {
      if (!this.listdata.length) {
        this.$message.warn({ content: '暂未添加任何商品', duration: 2 })
        return
      }
      this.$emit('validStep2')
    },
    //修改列表信息aList为修改的记录
    onChangeInput (aList) {
    },
    // 保存详细信息
    async saveObjInfo (order) {
      let listdata = JSON.parse(JSON.stringify(this.listdata))
      for (const item of listdata) {
        delete item.action;
        item.purOrderPid = order.pid
        item.purOrderNo = order.purOrderNo
      }
      console.log(listdata)
      let key = 'updatable'
      this.$message.loading({ content: '提交中', key, duration: 0 })
      let res = await saveOederGoods(listdata)
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '提交成功', key, duration: 3 })
        this.closeModal()
        this.$emit('onSubmit')
      } else {
        this.$message.error({ content: '提交失败，请检查提交内容', key, duration: 3 })
        this.$emit('onSubmitError')
      }
    },
    onAction (text, record, index) {
      console.log(text, record, index)
      if (text == '删除') {
        this.listdata.splice(index, 1)
      }
    },
  },
}
</script>

<style>
.recordBox {
  width: 100%;
  min-height: 80px;
}
.stepBox {
  width: 100%;
  height: 100%;
  position: relative;
}
.cont {
  padding-left: 5px;
  max-height: calc(70vh - 40px);
  overflow-y: scroll;
}
.btnBox {
  height: 7vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  /* border: 1px solid #eee; */
  position: absolute;
  bottom: 0px;
}
</style>